//
//  HMEditViewController.m
//  HeartMark
//
//  Created by rimi on 2016/11/8.
//  Copyright © 2016年 黄华强. All rights reserved.
//

#import "HMEditViewController.h"
#import "HMAlertView.h"

@interface HMEditViewController ()<UITextViewDelegate>

@property (nonatomic,strong) UITextView *editTextView;
@property (nonatomic,strong) UIView *tabBarView;
@property (nonatomic,strong) UIButton *keyboardBtn;
//是否公开的标识字符
@property (nonatomic,copy) NSString *isPublic;
@property (nonatomic,copy) NSString *authorName;

@end


@implementation HMEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}


- (void)setupUI {
    [self.view addSubview:self.editTextView];
    [self tabBarView];
    self.title = @"笔记编辑";
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
}

- (void)loadData {
    
    
    AVUser *currentUser = [AVUser currentUser];
    NSString *userId = currentUser[@"objectId"];
    
    self.authorName = currentUser[@"username"];
    
    
    AVQuery *query = [AVQuery queryWithClassName:@"userIcon"];
    [query whereKey:@"userId" equalTo:userId];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            AVObject *userIconObj = [objects lastObject];
            NSString *nickName = userIconObj[@"userNickName"];
            if (!nickName) {
                nickName = @"";
            }
            self.authorName = nickName;
        }
       
       
    }];

}


- (void)changeIsPublic:(UIButton *)button {
    if ([_isPublic isEqualToString:@"NO"]) {
        [button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
        _isPublic = @"YES";
        [button setImage:[UIImage imageNamed:@"单选框选中"] forState:(UIControlStateNormal)];
    } else {
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        _isPublic = @"NO";
        [button setImage:[UIImage imageNamed:@"单选框"] forState:(UIControlStateNormal)];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

//重写系统的一些方法
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
    //注册监听键盘弹出回收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationWithKeyboard:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
    
}

#pragma mark - 一些业务逻辑的方法
//通知回调方法
- (void)notificationWithKeyboard:(NSNotification *)notify {
    CGRect keyBoardRect = [notify.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat keyBoardY = keyBoardRect.origin.y;
    
    if (keyBoardY < SCREEN_HEIGHT) {
        [_keyboardBtn setImage:[UIImage imageNamed:@"键盘弹出"] forState:(UIControlStateNormal)];
    } else {
        [_keyboardBtn setImage:[UIImage imageNamed:@"键盘收起"] forState:(UIControlStateNormal)];
    }
    
    self.tabBarView.frame = CGRectMake(0, keyBoardY - 44, SCREEN_WIDTH, 44);
    self.editTextView.frame = CGRectMake(SCREEN_WIDTH * 0.03, 80, SCREEN_WIDTH * 0.94, keyBoardY - 124);
}
//键盘按钮回调
- (void)tabBarBtnClicked:(UIButton *)button {
    switch (button.tag) {
        case 100:
            [self.editTextView endEditing:YES];
            [button setImage:[UIImage imageNamed:@"键盘收起"] forState:(UIControlStateNormal)];
            break;
        case 101:{
            NSRange range = self.editTextView.selectedRange;
            
            NSUInteger location  = self.editTextView.selectedRange.location;
            NSString * textStr = self.editTextView.text;
            NSString *myStr = @"        ";
            NSString *resultStr = [NSString stringWithFormat:@"%@%@%@",[textStr substringToIndex:location],myStr,[textStr substringFromIndex:location]];
            self.editTextView.text = resultStr;
            range.location = range.location + 8;
            
            self.editTextView.selectedRange = NSMakeRange(range.location,0);
            break;
        }
        case 102:
            if (_note) {
                UIAlertController* alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认修改？" preferredStyle:UIAlertControllerStyleAlert];
                
                [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                    [self changeNotes];
                }]];
                [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                
                [self presentViewController:alertVc animated:YES completion:nil];
                
                
                
            } else {
                [self saveNote];
            }
            break;
        default:
            break;
    }
    
}

- (void)changeNotes {
    AVObject *todo =[AVObject objectWithClassName:@"note" objectId:_note.noteId];
    // 修改属性
    [todo setObject:_editTextView.text forKey:@"content"];
    [todo setObject:_isPublic forKey:@"isPublic"];
    // 保存到云端
    [todo saveInBackground];
    self.changeNote(_editTextView.text,_isPublic);
    [self.navigationController popViewControllerAnimated:YES];
}

//创建笔记
- (void)saveNote {
    if ([_editTextView.text isEqualToString:@""]) {
        [self setAlertVc:@"笔记为空,不能保存哦"];
    }else{
    
    
    NSNumber *collectNumber = @0;
    AVObject *note = [[AVObject alloc] initWithClassName:@"note"];// 构建对象
    
    [note setObject:self.authorName forKey:@"authorName"];//作者姓名
    [note setObject:self.authorId forKey:@"authorId"];// 设置作者id
    [note setObject:_editTextView.text forKey:@"content"];// 设置内容
    [note setObject:_isPublic forKey:@"isPublic"];
    [note setObject:collectNumber forKey:@"collectNumber"];
    [note setObject:@"NO" forKey:@"isDelete"];
        //NSDictionary *dict = @{@"authorName":self.authorName,@"authorId":self.authorId,@"content":_editTextView.text,@"isPublic":_isPublic,@"collectNumber":collectNumber,@"isDelete":@"NO"};
        
    [note saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        NSDate *currDate = [NSDate date];
        if (succeeded) {
            // 存储成功
            
            NSDictionary *objDict = @{@"updatedAt":currDate,@"content":note[@"content"],@"objectId":note[@"objectId"],@"isPublic":_isPublic};
            self.addNote(objDict);
            [self.navigationController popViewControllerAnimated:YES];
        } else {
//             NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//            NSString *isSave = [userDefaults objectForKey:@"noteSaveArr"];
//            if ([isSave isEqualToString:@"YES"])  {
//               NSArray *notArray = [userDefaults objectForKey:@"notSaveArray"];
//                NSMutableArray *muNArr = [NSMutableArray arrayWithArray:notArray];
//                [muNArr addObject:dict];
//                [userDefaults setObject:muNArr forKey:@"notSaveArray"];
//            } else {
//                NSMutableArray *notSaveArr = [NSMutableArray arrayWithObject:dict];
//                [userDefaults setObject:notSaveArr forKey:@"notSaveArray"];
//                [userDefaults setObject:@"YES" forKey:@"noteSaveArr"];
//            }

            
            [HMAlertView bottomAlertView:@"网络异常，数据可能会丢失！"];
            
            NSDictionary *objDict = @{@"updatedAt":currDate,@"content":_editTextView.text,@"objectId":@"qwerty",@"isPublic":_isPublic};
            self.addNote(objDict);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    }
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{     //其实你可以加在这个代理方法中。当你将要编辑的时候。先执行这个代理方法的时候就可以改变间距了。这样之后输入的内容也就有了行间距。
    
    if (textView.text.length < 1) {
        textView.text = @"间距";
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    paragraphStyle.lineSpacing = 8;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 
                                                                  NSFontAttributeName:[UIFont systemFontOfSize:TEXT_FONT],
                                 
                                                                  NSParagraphStyleAttributeName:paragraphStyle
                                                                  
                                                                  };
    
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
    if ([textView.text isEqualToString:@"间距"]) {           //之所以加这个判断是因为再次编辑的时候还会进入这个代理方法，如果不加，会把你之前输入的内容清空。你也可以取消看看效果。
        textView.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];//主要是把“间距”两个字给去了。
    }
    return YES;
}



#pragma mark - 懒加载方法集合
- (UITextView *)editTextView {
    if (!_editTextView) {
        _editTextView = [[UITextView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.03, 80, SCREEN_WIDTH * 0.94, SCREEN_HEIGHT - 124)];
        
        _editTextView.showsVerticalScrollIndicator = NO;
        _editTextView.delegate = self;
        if (_note) {
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineSpacing = 8; //行距
            paragraphStyle.firstLineHeadIndent = 0;
            
            NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:SCREEN_WIDTH * 0.04], NSParagraphStyleAttributeName:paragraphStyle};
            
            _editTextView.attributedText = [[NSAttributedString alloc]initWithString: _note.content attributes:attributes];

        }
        
        
        
    }
    
    return _editTextView;
}

- (UIView *)tabBarView {
    
    if (!_tabBarView) {
        _tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 44, SCREEN_WIDTH, 44)];
        _tabBarView.backgroundColor = [[UIColor alloc] initWithRed:0.95 green:0.95 blue:0.95 alpha:1];;
        //回收键盘按钮
        _keyboardBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 70, 2, 48, 40)];
        _keyboardBtn.tag = 100;
        [_keyboardBtn setImage:[UIImage imageNamed:@"键盘收起"] forState:(UIControlStateNormal)];
        [_keyboardBtn addTarget:self action:@selector(tabBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarView addSubview:_keyboardBtn];
        //清除按钮
        UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 8, 40, 28)];
        [cancelBtn setImage:[UIImage imageNamed:@"Tab"] forState:(UIControlStateNormal)];
        cancelBtn.tag = 101;
        [cancelBtn addTarget:self action:@selector(tabBarBtnClicked:) forControlEvents:(UIControlEventTouchUpInside)];
        [_tabBarView addSubview:cancelBtn];
        
        //保存按钮
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.6, 4, 40, 36)];
        [saveBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        saveBtn.backgroundColor = [UIColor greenColor];
        saveBtn.tag = 102;
        if (_note) {
            [saveBtn setTitle:@"修改" forState:(UIControlStateNormal)];
        } else {
            [saveBtn setTitle:@"保存" forState:(UIControlStateNormal)];
        }
        
        [saveBtn addTarget:self action:@selector(tabBarBtnClicked:) forControlEvents:(UIControlEventTouchUpInside)];
        [_tabBarView addSubview:saveBtn];
        
        //是否公开按钮
        
        _isPublic = @"NO";
        
        UIButton *isPublicBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.28, 4, 60, 36)];
        
        [isPublicBtn setImage:[UIImage imageNamed:@"单选框"] forState:(UIControlStateNormal)];
        [isPublicBtn setTitle:@"公开" forState:(UIControlStateNormal)];
        [isPublicBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [isPublicBtn addTarget:self action:@selector(changeIsPublic:) forControlEvents:(UIControlEventTouchUpInside)];
        [_tabBarView addSubview:isPublicBtn];
        
        if (_note) {
            _isPublic = _note.isPublic;
            if ([_isPublic isEqualToString:@"YES"]) {
                [isPublicBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
                
                [isPublicBtn setImage:[UIImage imageNamed:@"单选框选中"] forState:(UIControlStateNormal)];
            } else {
                
                
                [isPublicBtn setImage:[UIImage imageNamed:@"单选框"] forState:(UIControlStateNormal)];
            }
        }
        
        
        [self.view addSubview:_tabBarView];
    }
    return _tabBarView;
}
//提示框
-(void)setAlertVc:(NSString*)string{
    UIAlertController* alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
    
}

@end
